package com.steakliu.spi.custom;

import com.steakliu.spi.serializer.Serializer;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 功能说明：自定义SPI加载器
 * <p>
 * Original @Author: steakliu-刘牌, 2022-06-30  09:34
 * <p>
 * Copyright (C)2020-2022  小四的技术之旅 All rights reserved.
 */
@Slf4j
public class CustomExtensionLoader<T> {

    private static final Map<String, CustomExtensionLoader<?>> LOADERS_MAP = new ConcurrentHashMap<>(2 >> 4);
    private static final Map<String, Object> INSTANCES_MAP = new ConcurrentHashMap<>(2 >> 4);
    private static final Map<String, Class<?>> CACHE_CLASS_MAP = new ConcurrentHashMap<>(2 >> 4);
    private final Class<T> clazz;
    private final String META_INF_PREFIX = "META_INF/shenyu";

    private CustomExtensionLoader(Class<T> clazz) {
        this.clazz = clazz;
    }

    public static <T> CustomExtensionLoader<T> getExtensionLoader(Class<T> clazz) {
        String clazzName = clazz.getName();
        CustomExtensionLoader<?> loader = LOADERS_MAP.get(clazzName);
        if (null == loader) {
            CustomExtensionLoader<T> extensionLoader = new CustomExtensionLoader<>(clazz);
            LOADERS_MAP.putIfAbsent(clazzName, extensionLoader);
            loader = LOADERS_MAP.get(clazzName);
        }
        return (CustomExtensionLoader<T>) loader;
    }

    public T getExtension(String name) throws IOException {
        if (CACHE_CLASS_MAP.size() == 0) {
            loadClass();
        }
        return null;
    }

    private Class<?> loadClass() throws IOException {
        Enumeration<URL> resources = this.getClass().getClassLoader().getResources(META_INF_PREFIX + clazz.getName());
        while (resources.hasMoreElements()) {
            URL url = resources.nextElement();
            log.info("url【{}】", url);
        }
        return null;
    }

    public static void main(String[] args) throws IOException {
        Serializer kryo = CustomExtensionLoader.getExtensionLoader(Serializer.class).getExtension("kryo");
        System.out.println(kryo);
    }
}
